/****************
 *@description:  礼物商品管理  myPocket/giftManage/index
 *@author: Xhd
 *@API: 陈浩天
 *@date: 2023-11-27 09:48:15
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from "react";
import TheQueryForm from "@/components/TheQueryForm";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheImage from "@/components/TheImage";
import TheButton from "@/components/TheButton";
import store from "@/store/store";
import { apiGiftInfoPage, apiGiftInfoModify } from "@/request/giftManage";

class GiftManage extends Component {
  constructor(props) {
    super(props)
    this.queryFormRef = React.createRef()
    this.state = {
      form_show: true,
      searchOption: [
        { field: "giftName", label: "礼物名称", placeholder: "礼物名称", required: false, rules: [], type: "Input", defaultValue: "", },
        { field: "giftStatus", label: "状态", placeholder: "请选择礼物状态", required: false, rules: [], type: "Select", options: [{ value: 0, label: "上架" }, { value: 1, label: "下架" },], },
      ],
      columns: [
        {
          title: "礼物ID",
          dataIndex: "giftId",
          key: "giftId",
        },
        {
          width: 200,
          title: "礼物名称",
          dataIndex: "giftName",
          key: "giftName",
          render: (text, record) => (
            <div style={{ wordWrap: 'break-word', wordBreak: 'break-word', width: 200 }}>
              <div style={{
                wordBreak: 'break-all',
                whiteSpace: 'pre-wrap'
              }}>
                {text}
              </div>
            </div>
          ),
        },
        {
          title: "礼物图",
          dataIndex: "giftImg",
          key: "giftImg",
          render: (text, record) => {
            return <TheImage src={text} width={"80px"} />
          }
        },
        {
          title: "礼物标价（宠币）",
          dataIndex: "giftPrice",
          key: "giftPrice",
          render: (text) => {
            return (Number(text) / 10).toString()
          }
        },
        {
          title: "排序",
          dataIndex: "giftSort",
          key: "giftSort",
          sorter: true,
          sortDirections: ["ascend", "descend"],
          defaultSortOrder: "ascend"
        },
        {
          title: "礼物状态",
          dataIndex: "giftStatus",
          key: "giftStatus",
          render: (text, record) => {
            return text === 0 ? "已上架" : "已下架"
          }
        },
        {
          title: "礼物标签",
          dataIndex: "giftTagImg",
          key: "giftTagImg",
          render: (text, record) => {
            return text ? <TheImage src={text} width={"80px"} /> : null
          }
        },
        {
          title: "单次最大购买数量",
          dataIndex: "giftBuySize",
          key: "giftBuySize",
        },
        {
          title: "上传时间",
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: "操作",
          fixed: "right",
          width: 300,
          render: (text, record) => {
            return (
              <div>
                <TheButton
                  haspermi={["myPocket:giftManage:detail"]}
                  onClick={() => this.props.history.push(`/myPocket/giftManage/detail/info/${record.giftId}`)}
                >
                  详情
                </TheButton>
                {(record.giftStatus === 1) && (
                  <TheButton
                    haspermi={["myPocket:giftManage:shelves"]}
                    onClick={() => this.putShelf(record, 0)}
                  >
                    上架
                  </TheButton>
                )}
                {record.giftStatus === 0 && (
                  <TheButton
                    haspermi={["myPocket:giftManage:shelves"]}
                    onClick={() => this.offShelf(record, 1)}
                  >
                    下架
                  </TheButton>
                )}
              </div>
            );
          },
        },
      ],
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      queryForm: {},
      sortType: 1,
    }
  }

  componentDidMount() {
    let searchParams = store.getState().searchValue;
    let { pageNo, pageSize, queryForm, pathName } = searchParams;
    if (searchParams && pageNo && pathName == "giftManage") {
      this.setState(
        {
          queryForm,
          pageData: {
            pageNo: pageNo,
            pageSize: pageSize,
          },
        },
        () => {
          this.queryFormRef.onSetDefault({
            ...queryForm,
          });
          this.getData();
        }
      );
    } else {
      this.getData();
    }
  }

  getData = async (values) => {
    const { sortType } = this.state
    let { pageNo, pageSize } = this.state.pageData;
    this.setState(
      {
        queryForm: values === undefined ? this.state.queryForm : { ...values },
      },
      async () => {
        let { ...form } = { ...this.state.queryForm };
        const params = {
          pageNo,
          pageSize,
          queryForm: { ...form, },
        };
        store.dispatch({
          type: "SaveSearchValues",
          data: {
            pathName: "giftManage",
            ...params,
          },
        });
        let res = await apiGiftInfoPage({
          sortType,
          pageNo,
          pageSize,
          ...form,
        });
        if (res.code === 0 && res.data) {
          this.setState({
            dataSource: res.data,
            pageData: { pageNo: res.pageNo, pageSize: res.pageSize },
            total: res.totalCount,
          });
        }
      }
    );
  };

  pageChange = (pageNo, pageSize) => {
    this.setState(
      {
        pageData: {
          pageNo,
          pageSize,
        },
      },
      () => {
        this.getData();
      }
    );
  }

  onFormSearch(values) {
    this.setState(
      {
        pageData: { pageNo: 1, pageSize: 10 },
      },
      () => {
        this.getData(values);
      }
    );
  }

  onReset() {
    this.setState(
      {
        queryForm: {},
      },
      () => {
        this.getData();
      }
    );
  }


  toAdd = () => {
    this.props.history.push(`/myPocket/giftManage/detail/add/${null}`);
  }

  putShelf = async (gift, giftStatus) => {
    let res = await apiGiftInfoModify({ ...gift, giftStatus })
    if (res.code === 0) {
      React.$message({
        type: "success",
        content: "已成功上架"
      })
      this.getData()
    }
  }

  offShelf = async (gift, giftStatus) => {
    let res = await apiGiftInfoModify({ ...gift, giftStatus })
    if (res.code === 0) {
      React.$message({
        type: "success",
        content: "已成功下架"
      })
      this.getData()
    }
  }

  toDelet = (giftId) => {
    React.$confirm({
      title: "删除确认",
      content: "确认删除该宠币商品吗",
      onOk: async () => {
        let res = await apiGiftInfoModify({ giftId, deleted: 1 })
        if (res.code === 0) {
          React.$message({
            type: "success",
            content: "删除成功"
          })
          this.pageChange(1, 10)
        }
      }
    })

  }

  handleTableChange = (pagination, filters, sorter) => {
    console.log(sorter.order);
    let sortType = 0
    switch (sorter.order) {
      case "ascend":
        sortType = 1
        break;
      case "descend":
        sortType = 2
        break;
      default:
        break;
    }
    this.setState({
      sortType
    }, () => {
      this.getData()
    })
  }

  render() {
    const { form_show, searchOption, columns, dataSource, pageData, total } = this.state
    return (<div className="p-layout-box">
      <TheQueryForm
        ref={(ref) => (this.queryFormRef = ref)}
        show={form_show}
        option={searchOption}
        onReset={() => this.onReset()}
        onGetValues={(values) => this.onFormSearch(values)}
      ></TheQueryForm>
      <div style={{ textAlign: "right", padding: "10px" }}>
        <TheButton haspermi={["myPocket:giftManage:add"]} type="primary" size="middle" onClick={() => this.toAdd()} >上传礼物</TheButton>
      </div>
      礼物列表
      <TheTable
        columns={columns}
        dataSource={dataSource}
        // onRow={
        //   record => {
        //     return {
        //       onClick: event => this.toDelet(record.giftId), // 点击行
        //     }
        //   }
        // }
        onChange={this.handleTableChange}
      />
      <ThePagination
        pageNo={pageData.pageNo}
        pageSize={pageData.pageSize}
        total={total}
        pageChange={this.pageChange}
      />
    </div>)
  }
}

export default GiftManage